package blogger.server.services;

import blogger.client.async.services.UserService;
import blogger.client.model.entity.User;
import blogger.client.model.entity.UserDetails;
import blogger.model.entity.UserEntity;
import blogger.model.utils.EMF;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import javax.persistence.EntityManager;
import javax.persistence.Query;


import java.util.List;
import java.util.LinkedList;

/**
 * Created by IntelliJ IDEA.
 * User: mega
 * Date: 24.12.2009
 * Time: 9:43:16
 * To change this template use File | Settings | File Templates.
 */
public class UserServiceImpl extends RemoteServiceServlet implements UserService {

    public long getCurrentUserId() {
        return (Long)this.getThreadLocalRequest().getSession(false).getAttribute("id");
    }

    public User getUserById(long id) {
        EntityManager em = EMF.get().createEntityManager();
        User user = null;
        try{
            Query query = em.createQuery("select u from UserEntity u where u.id = :uid");
            query.setParameter("uid",id);
            UserEntity userEntity = (UserEntity) query.getSingleResult();
            user = userEntity.toUserGwt();
        }finally {
            em.close();
        }
        return user;
    }

    public List<User> getUsers(List<Long> ids) {
        List<User> users = new LinkedList<User>();
        EntityManager em = EMF.get().createEntityManager();
        StringBuffer qS = new StringBuffer("SELECT u FROM UserEntity u WHERE ");
        for(int i=0; i<ids.size(); ++i){
            if(i<ids.size() - 1)
                qS.append(" u.id = " + ids.get(i) + " OR ");
            else
                qS.append(" u.id = " + ids.get(i));
        }
        Query query = em.createQuery(qS.toString());
        List<UserEntity>list = query.getResultList();
        for(UserEntity entity : list)
            users.add(entity.toUserGwt());
        return users;
    }

    public UserDetails getUserDetailsById(long id) {
        return null;
    }
}